﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace PayloadTracker.VOR
{
    [Serializable]
    public class VORCollection : IEnumerable<VOR>
    {
        List<VOR> m_VORs;
        public List<VOR> VORs
        {
            get { return m_VORs; }
            set { m_VORs = value; }
        }

        public VORCollection()
        {
            m_VORs = new List<VOR>();
        }
        /// <summary>
        /// Save to file
        /// </summary>
        /// <param name="Filename"></param>
        public void Save(string Filename)
        {
            var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(VORCollection));
            var writerSettings = new System.Xml.XmlWriterSettings();
            writerSettings.Indent = true;
            writerSettings.OmitXmlDeclaration = true;
            var writer = System.Xml.XmlWriter.Create(Filename, writerSettings);
            xmlSerializer.Serialize(writer, this);

            writer.Flush();
            writer.Close();
        }
        /// <summary>
        /// Load from file
        /// </summary>
        /// <param name="Filename"></param>
        public static VORCollection Load(string Filename)
        {
            if (!System.IO.File.Exists(Filename))
            {
                Logger.LOG.Error("VORCollection does not exist. Creating new.", true);
                return new VORCollection();
            }
            try
            {
                var xrs = new System.Xml.XmlReaderSettings();
                xrs.CloseInput = true;
                var xmlDeserializer = new System.Xml.Serialization.XmlSerializer(typeof(VORCollection));
                using (var reader = System.Xml.XmlReader.Create(System.IO.File.OpenRead(Filename), xrs))
                    return xmlDeserializer.Deserialize(reader) as VORCollection;
            }
            catch (System.Exception ex)
            {
                Logger.LOG.Warn("Error loading VORCollection data from: " + Filename + ".\nDue to " + ex.Message + "\nCreating new.");
                Logger.LOG.Error("Error loading VORCollection data from: " + Filename + ".\nDue to " + ex + "\nCreating new.");
                return new VORCollection();
            }
        }


        #region IEnumerableMembers

        public void Add(object o)
        {
            if (o.GetType() != typeof(VOR))
                throw new Exception("Invalid type.");

            VOR f = ((VOR)o);

            m_VORs.Add(f);

        }
        public IEnumerator<VOR> GetEnumerator()
        {
            return m_VORs.GetEnumerator();
        }
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return m_VORs.GetEnumerator();
        }

        #endregion
    }
}